package com.lagou.edu.controller;

import com.lagou.edu.pojo.LagouToken;
import com.lagou.edu.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 注册
     * @param email
     * @param password
     * @param code
     * @return
     */
    @PostMapping("/register")
    public boolean register(String email, String password, String code){
        return userService.register(email,password,code);
    }

    /**
     * 检查邮箱是否已经被注册
     * @param email
     * @return
     */
    @PostMapping("/isRegister")
    public boolean isRegister(String email){
        return userService.checkRegister(email);
    }

    /**
     * 登录
     * @param response
     * @param email
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String login(HttpServletResponse response, String email,String password)  {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        LagouToken lagouToken = userService.login(email,password);
        if(lagouToken != null){
            String uuid = UUID.randomUUID().toString();
            LagouToken token = new LagouToken();
            token.setToken(uuid);
            token.setEmail(email);
            token.setPassword(password);
//            userService.createToken(token);
            //同时把token存入cookie
            Cookie cookie = new Cookie("token", lagouToken.getToken());
            cookie.setPath("/");
            response.addCookie(cookie);
            return lagouToken.getEmail();
        }else{
            return "";
        }
    }

    /**
     * 根据token 查询用户邮箱
     * @param token
     * @return
     */
    @GetMapping("/info/{token}")
    public String info(@PathVariable String token){
        String email = userService.info(token);
        return email;
    }

}
